package com.dj.product.k2faas.controller.function;

import com.dj.product.k2faas.common.dto.IdResponse;
import com.dj.product.k2faas.dto.function.*;
import com.dj.product.k2faas.service.function.FunctionService;
import com.dj.product.k2faas.validator.function.FunctionValidator;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

/**
 * Created by 丁建 on 2025/9/23 16:38
 *
 * @author 丁建
 */
@RestController
@RequestMapping({ "/functions/" })
public class FunctionController {

    @Autowired
    private FunctionValidator functionValidator;

    @Autowired
    private FunctionService functionService;

    @PostMapping
    public IdResponse<Long> add(@RequestBody @Valid CreateFunctionRequest function) {
        functionValidator.assertNameAvailable(function.getName());

        var id = functionService.add(function);
        return new IdResponse<Long>().setId(id);
    }

    @PutMapping({ "/{id}/" })
    public void edit(@RequestBody @Valid UpdateFunctionRequest function, @PathVariable long id) {
        functionValidator.assertNameAvailable(id, function.getName());
        functionValidator.assertFunctionNotRunning(id);

        functionService.edit(function);
    }

    @GetMapping({ "/{id}/" })
    public FunctionResponse findById(@PathVariable long id) {
        return functionService.findById(id);
    }

    @GetMapping
    public Page<FunctionResponse> findAll(@RequestParam(required = false) String keyword, Pageable pageable) {
        return functionService.findAll(keyword, pageable);
    }

    @PostMapping({ "/{id}/actions/disable/" })
    public void disable(@PathVariable long id) {
        functionService.disable(id);
    }

    @PostMapping({ "/{id}/actions/start/" })
    public void start(@PathVariable long id) {
        functionValidator.assertFunctionNotRunning(id);
        functionService.start(id);
    }

    @PostMapping({ "/{id}/actions/stop/" })
    public void stop(@PathVariable long id) {
        functionValidator.assertFunctionIsRunning(id);
        functionService.stop(id);
    }

    @PostMapping({ "/actions/test/" })
    public TestFunctionResponse testConnection(@RequestBody @Valid TestFunctionRequest request) {
        return functionService.testFunction(request);
    }

}
